package com.landiao.ctrler.weixin;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.landiao.common.Constant;
import com.landiao.common.Constant.PayResult;
import com.landiao.common.Constant.WxTradeType;
import com.landiao.common.factory.ResultMsgFactory;
import com.landiao.common.pojo.EmpAppointTime;
import com.landiao.common.pojo.Page;
import com.landiao.common.pojo.PageMap;
import com.landiao.common.pojo.Querier;
import com.landiao.common.pojo.RecordDetail;
import com.landiao.common.pojo.ResultMsg;
import com.landiao.common.utils.CodecUtils;
import com.landiao.common.utils.CommUtil;
import com.landiao.common.utils.DateUtil;
import com.landiao.common.utils.IpUtil;
import com.landiao.common.weixin.WxConsts;
import com.landiao.common.weixin.WxErrorException;
import com.landiao.common.weixin.WxMpService;
import com.landiao.common.weixin.bean.WxJsapiSignature;
import com.landiao.common.weixin.bean.WxMenu;
import com.landiao.common.weixin.bean.WxMenu.WxMenuButton;
import com.landiao.common.weixin.bean.WxMpTemplateData;
import com.landiao.common.weixin.bean.WxMpTemplateMessage;
import com.landiao.common.weixin.bean.WxMpUser;
import com.landiao.common.weixin.bean.WxMpXmlMessage;
import com.landiao.common.weixin.bean.WxMpXmlOutTextMessage;
import com.landiao.ctrler.BaseCtrler;
import com.landiao.entities.Appointment;
import com.landiao.entities.AppointmentServiceItem;
import com.landiao.entities.CouponReceive;
import com.landiao.entities.Employee;
import com.landiao.entities.Holiday;
import com.landiao.entities.IdentifyCode;
import com.landiao.entities.OrderInfo;
import com.landiao.entities.OrderSchedule;
import com.landiao.entities.PackagePrice;
import com.landiao.entities.PayFlow;
import com.landiao.entities.SendTemplate;
import com.landiao.entities.ServiceItem;
import com.landiao.entities.ServiceItemPrice;
import com.landiao.entities.Shop;
import com.landiao.entities.Vip;
import com.landiao.entities.Works;
import com.landiao.service.AppointmentService;
import com.landiao.service.CouponReceiveService;
import com.landiao.service.CouponService;
import com.landiao.service.EmployeeService;
import com.landiao.service.HairdoRecordService;
import com.landiao.service.HolidayService;
import com.landiao.service.IdentifyCodeService;
import com.landiao.service.OrderInfoService;
import com.landiao.service.OrderScheduleService;
import com.landiao.service.PackageService;
import com.landiao.service.PayFlowService;
import com.landiao.service.SendTemplateService;
import com.landiao.service.ServiceItemService;
import com.landiao.service.ShopService;
import com.landiao.service.SysConfigService;
import com.landiao.service.VipService;
import com.landiao.service.WorksService;

/**
 * 功能说明:会员微信端
 */
@Controller
@RequestMapping("/weixin/vip")
public class WxVipCtrler extends BaseCtrler{
	
	private static final String EMPLOYEE_ORDER_URL="weixin/employee/myAppoint";
	
	@Autowired
	@Qualifier("employeeWxService")
	private WxMpService employeeWxService;

	@Autowired
	@Qualifier("vipWxService")
	private WxMpService vipWxService;
	
	@Autowired
	private VipService vipService;
	
	@Autowired
	private IdentifyCodeService identifyCodeService;
	
	@Autowired
	private HairdoRecordService hairdoRecordService;
	
	@Autowired
	private OrderInfoService orderInfoService;
	
	@Autowired
	private AppointmentService appointService;
	
	@Autowired
	private OrderScheduleService scheService;
	
	@Autowired
	private ShopService shopService;
	
	@Autowired
	private PackageService packageService;
	
	@Autowired
	private ServiceItemService itemService;
	
	@Autowired
	private EmployeeService employeeService;
	
	@Autowired
	private WorksService worksService;
	
	@Autowired
	private HolidayService holidayService;
	
	@Autowired
	private PayFlowService payFlowService;
	
	@Autowired
	private CouponReceiveService couponReceiveService;
	
	@Autowired
	private CouponService couponService;
	
	@Autowired
	private SysConfigService sysConfigService;
	
	@Autowired
	private SendTemplateService sendTempService;
	
	@RequestMapping(method = RequestMethod.GET)
	public void index(HttpServletRequest request,String signature,String timestamp,String nonce,String echostr,HttpServletResponse response){
		try {
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");
		
			PrintWriter out = response.getWriter();
			if(vipWxService.checkSignature(timestamp, nonce, signature)){
				log.error("echostr:{}",echostr);
				out.print(echostr);
			}else{
				out.print("error");
			}
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping(method = RequestMethod.POST)
	public void index(HttpServletRequest request,HttpServletResponse response){
		try {
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");
			WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(request.getInputStream());
			log.debug("wxInXml:{}",inMessage.toString());
			String resp = "success";
			if (inMessage.getMsgType().equals(WxConsts.XML_MSG_EVENT)) {//事件
				if(inMessage.getEvent().equals(WxConsts.EVT_SUBSCRIBE)){//关注
					//WxMpUser wxUser = vipWxService.userInfo(inMessage.getFromUserName(), null);
					WxMpXmlOutTextMessage text = new WxMpXmlOutTextMessage();
					text.setContent(vipWxService.getWxMpConfigStorage().getWelcome());
					text.setCreateTime(System.currentTimeMillis()/1000l);
					text.setFromUserName(inMessage.getToUserName());
					text.setToUserName(inMessage.getFromUserName());
					resp=text.toXml();
				}
				if(inMessage.getEvent().equals(WxConsts.EVT_UNSUBSCRIBE)){//取消关注
					
				}
			}
			PrintWriter out = response.getWriter();
			out.print(resp);
			out.flush();
			out.close();
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
		}
	}
	
	@RequestMapping("menu")
	@ResponseBody
	public String menu(HttpServletRequest request){
		try {
			WxMenu wxMenu = new WxMenu();
			WxMenuButton button1 = new WxMenuButton();
			button1.setType(WxConsts.BUTTON_VIEW);
			button1.setUrl(this.webSite+"weixin/vip/order");
			button1.setName("预约服务");
			
			WxMenuButton button2 = new WxMenuButton();
			button2.setName("个人中心");
			
			WxMenuButton button21 = new WxMenuButton();
			button21.setType(WxConsts.BUTTON_VIEW);
			button21.setUrl(this.webSite+"weixin/vip/vipCard");
			button21.setName("会员卡");
			
			WxMenuButton button22 = new WxMenuButton();
			button22.setType(WxConsts.BUTTON_VIEW);
			button22.setUrl(this.webSite+"weixin/vip/record");
			button22.setName("消费记录");
			
			WxMenuButton button23 = new WxMenuButton();
			button23.setType(WxConsts.BUTTON_VIEW);
			button23.setUrl(this.webSite+"weixin/vip/myOrder");
			button23.setName("我的预约");
			
			WxMenuButton button24 = new WxMenuButton();
			button24.setType(WxConsts.BUTTON_VIEW);
			button24.setUrl(this.webSite+"weixin/vip/coupon");
			button24.setName("我的卡券");
			
			WxMenuButton button25 = new WxMenuButton();
			button25.setType(WxConsts.BUTTON_VIEW);
			button25.setUrl(this.webSite+"weixin/vip/myEvaluate");
			button25.setName("我的评价");
			
			button2.getSub_button().add(button21);
			button2.getSub_button().add(button22);
			button2.getSub_button().add(button23);
			button2.getSub_button().add(button24);
			button2.getSub_button().add(button25);
			
			WxMenuButton button3 = new WxMenuButton();
			button3.setName("蓝调社区");
			
			WxMenuButton button31 = new WxMenuButton();
			button31.setType(WxConsts.BUTTON_VIEW);
			button31.setUrl(this.webSite+"weixin/vip/service");
			button31.setName("服务项目");
			
			WxMenuButton button32 = new WxMenuButton();
			button32.setType(WxConsts.BUTTON_VIEW);
			button32.setUrl(this.webSite+"weixin/vip/add");
			button32.setName("会员注册");
			
			WxMenuButton button33 = new WxMenuButton();
			button33.setType(WxConsts.BUTTON_VIEW);
			button33.setUrl(this.webSite+"weixin/vip/test/vip_card");
			button33.setName("蓝调社区");
			
			button3.getSub_button().add(button31);
			button3.getSub_button().add(button32);
			button3.getSub_button().add(button33);
			
			wxMenu.getButton().add(button1);
			wxMenu.getButton().add(button2);
			wxMenu.getButton().add(button3);
			
			log.debug(wxMenu.toJson());
			// 设置菜单
			vipWxService.menuCreate(wxMenu);
			
			//添加模板
			if(Constant.VIP_TEMP_MAP.size()==0){
				vipWxService.templateSetIndustry(Constant.industry_id1, Constant.industry_id2);
				String msgid1 = vipWxService.templateAdd(Constant.TEMP_ID_ORDER_SUCCESS);
				String msgid2 = vipWxService.templateAdd(Constant.TEMP_ID_ORDER_FAIL);
				String msgid3 = vipWxService.templateAdd(Constant.TEMP_ID_PAY_SUCCESS);
				
				SendTemplate temp1 = new SendTemplate();
				temp1.setCompId(Constant.comp.getCompId());
				temp1.setSendTemplateId(CodecUtils.getUUID());
				temp1.setOriginNo(Constant.TEMP_ID_ORDER_SUCCESS);
				temp1.setPublicNo("VIP");
				temp1.setTemplateId(msgid1);
//				temp1.setTemplateType(templateType);
				temp1.setTitle("预约成功通知");
				
				this.sendTempService.save(temp1);
				
				Constant.EMPLOYEE_TEMP_MAP.put(Constant.TEMP_ID_ORDER_SUCCESS, temp1);
				
				SendTemplate temp2 = new SendTemplate();
				temp2.setCompId(Constant.comp.getCompId());
				temp2.setSendTemplateId(CodecUtils.getUUID());
				temp2.setOriginNo(Constant.TEMP_ID_ORDER_FAIL);
				temp2.setPublicNo("VIP");
				temp2.setTemplateId(msgid2);
//				temp2.setTemplateType(templateType);
				temp2.setTitle("预约失败通知");
				
				this.sendTempService.save(temp2);
				
				Constant.EMPLOYEE_TEMP_MAP.put(Constant.TEMP_ID_ORDER_FAIL, temp2);
				
				SendTemplate temp3 = new SendTemplate();
				temp3.setCompId(Constant.comp.getCompId());
				temp3.setSendTemplateId(CodecUtils.getUUID());
				temp3.setOriginNo(Constant.TEMP_ID_PAY_SUCCESS);
				temp3.setPublicNo("VIP");
				temp3.setTemplateId(msgid3);
//				temp3.setTemplateType(templateType);
				temp3.setTitle("订单支付成功");
				
				this.sendTempService.save(temp3);
				
				Constant.EMPLOYEE_TEMP_MAP.put(Constant.TEMP_ID_PAY_SUCCESS, temp3);
			}
		} catch (WxErrorException e) {
			log.error(e.getMessage());
			return e.getMessage();
		}
		return "success";
	}

	@RequestMapping(value = "add", method = RequestMethod.GET)
	public String add(Model model,String backUrl,HttpSession session, RedirectAttributes redirectAttr) {
		if(StringUtils.isNotBlank(backUrl))
			model.addAttribute("backUrl", backUrl);
		if(session.getAttribute("wxVip")==null){
			return viewName("register");
		}else{
			redirectAttr.addFlashAttribute("resultMsg", ResultMsgFactory.success("您已注册"));
			return redirectToUrl(viewName("vipCard"));
		}
	}
	
	@RequestMapping(value = "save", method = RequestMethod.POST)
	@ResponseBody
	public ResultMsg save(Vip vip,String identifyCodeId,String verifyCode,HttpSession session) {
		try{
			Date timenow = new Date();
			IdentifyCode identifyCode = this.identifyCodeService.getById(identifyCodeId);
//verifyCode = identifyCode.getCode();//验证码暂时不验证
			if(identifyCode!=null&&identifyCode.getCode().equals(verifyCode)&&identifyCode.getIsUsed().equals(Constant.IDENTIFY_CODE_ISUSED_NO)){
				if(timenow.getTime()-identifyCode.getCreTime().getTime()>10*60*1000){//验证码有效期5分钟
					return ResultMsgFactory.fail("验证码已过期");
				}
			}else{
				return ResultMsgFactory.fail("验证码错误");
			}
			if(!identifyCode.getPhone().equals(vip.getPhoneNo())){
				return ResultMsgFactory.fail("手机号码不一致");
			}
			identifyCode.setIsUsed(Constant.IDENTIFY_CODE_ISUSED_YES);
			identifyCode.setStatedate(timenow);
			this.identifyCodeService.update(identifyCode);
			
			WxMpUser wxUser = (WxMpUser)session.getAttribute("wxVipUser");
			vip.setCompId(Constant.comp.getCompId());
			vip.setOperId(wxUser.getOpenid());
//			vip.setNickname(wxUser.getNickname());
//			vip.setSex(new Integer(2).equals(wxUser.getSex())?"F":"M");
			Vip saveVip = this.vipService.saveFromWx(vip);
			session.setAttribute("wxVip", saveVip);
		}catch(Exception e){
			e.printStackTrace();
			log.error("注册失败：{}",e.getMessage());
			return ResultMsgFactory.fail("注册失败");
		}
		return ResultMsgFactory.success("注册成功");
	}
	
	@RequestMapping(value = "vipCard")
	public String vipCard(Model model,HttpSession session,HttpServletRequest request) {
		// TODO Auto-generated method stub
		Vip vip = (Vip)session.getAttribute("wxVip");
		model.addAttribute("vip", vip);
		model.addAttribute("hairdoRecord", this.hairdoRecordService.getMaxNestDate(vip.getVipId()));
		model.addAttribute("appid", vipWxService.getWxMpConfigStorage().getAppId());
		try {
			StringBuffer url = request.getRequestURL();
			if (request.getQueryString() != null) {
				url.append("?");
				url.append(request.getQueryString());
			}
			WxJsapiSignature sign = vipWxService.createJsapiSignature(url.toString());
			model.addAttribute("sign", sign);
		} catch (WxErrorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		log.debug(request.getRequestURL().toString());
		return viewName("vip_card");
	}
	
	@RequestMapping(value = "record")
	public String record(Model model,HttpSession session) {
		// TODO Auto-generated method stub
		return viewName("record");
	}
	
	@RequestMapping(value = "recordPage")
	@ResponseBody
	public Page<RecordDetail> recordPage(Model model,HttpSession session,Querier querier) {
		// TODO Auto-generated method stub
		Vip vip = (Vip)session.getAttribute("wxVip");
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setVipId(vip.getVipId());
		
		Page<OrderInfo> page = this.orderInfoService.queryByPageFromWx(querier, orderInfo);
		//转为页面显示的page
		Page<RecordDetail> pageMap = new Page<>();
		pageMap.setPage(page.getPage());
		pageMap.setPageSize(page.getPageSize());
		pageMap.setRecords(page.getRecords());
		pageMap.setTotal(page.getTotal());
		if(page.getRows()!=null&&page.getRows().size()>0){
			Map<String, RecordDetail> map = new LinkedHashMap<>();
    		for(OrderInfo info : page.getRows()){
    			String month = DateUtil.date2Str(info.getCreTime(), "yyM");
    			info.setCreDateStr(CommUtil.formatDateLocale(info.getCreTime()));
    			RecordDetail tmp= map.get(month);
    			if(tmp==null){
    				tmp = new RecordDetail();
    				tmp.setMonth(month);
    				tmp.setList(new ArrayList<OrderInfo>());
    				map.put(month, tmp);
    			}
    			tmp.getList().add(info);
    		}
    		pageMap.setRows(new ArrayList<RecordDetail>(map.values()));
    	}
		return pageMap;
	}
	
	@RequestMapping(value = "order")
	public String order(Model model,HttpSession session,HttpServletRequest request) {
		// TODO Auto-generated method stub
		Vip vip = (Vip)session.getAttribute("wxVip");
		List<Shop> shopList = this.shopService.getShopListByCompId(vip.getCompId());
		model.addAttribute("shopList", shopList);
		if(vip.getShopId()!=null){
			model.addAttribute("vipShopId", vip.getShopId());
		}
		String workHour = this.sysConfigService.getSysConfigMap().get(Constant.SysConfigItemEnum.WORK_HOUR.toString()).getVal1();
		String OffWorkHour = this.sysConfigService.getSysConfigMap().get(Constant.SysConfigItemEnum.OFF_WORK_HOUR.toString()).getVal1();
		Integer intOffWorkHour = Integer.valueOf(OffWorkHour);
		Integer interval = Integer.valueOf(this.sysConfigService.getSysConfigMap().get(Constant.SysConfigItemEnum.APPOINTMENT_INTERVAL.toString()).getVal1());
		
		List<String> orderTime = new ArrayList<>();
		int hour = Integer.valueOf(workHour);
		while(hour<intOffWorkHour&&hour<24){
			orderTime.add(hour+":00");
			hour += interval;
		}
		model.addAttribute("orderTime", orderTime);
		model.addAttribute("advanceNum", this.sysConfigService.getSysConfigMap().get(Constant.SysConfigItemEnum.APPOINTMENT_ADVANCE.toString()).getVal1());
		
		model.addAttribute("appid", vipWxService.getWxMpConfigStorage().getAppId());
		try {
			StringBuffer url = request.getRequestURL();
			if (request.getQueryString() != null) {
				url.append("?");
				url.append(request.getQueryString());
			}
			WxJsapiSignature sign = vipWxService.createJsapiSignature(url.toString());
			model.addAttribute("sign", sign);
		} catch (WxErrorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return viewName("order");
	}
	
	@RequestMapping(value = "orderSave", method = RequestMethod.POST)
	@ResponseBody
	public ResultMsg orderSave(Appointment appoint,AppointmentServiceItem appointServiceItem,HttpSession session) {
		// TODO Auto-generated method stub
		try{
			Vip vip = (Vip)session.getAttribute("wxVip");
			
			appoint.setAppointmentId(CodecUtils.getUUID());
			appoint.setCompId(vip.getCompId());
			appoint.setVipId(vip.getVipId());
			
			appointServiceItem.setAppointmentId(appoint.getAppointmentId());
			appointServiceItem.setAppointmentServiceItemId(CodecUtils.getUUID());
			appointServiceItem.setCompId(vip.getCompId());
			
			SendTemplate temp = Constant.EMPLOYEE_TEMP_MAP.get(Constant.TEMP_ID_ORDER_EMPLOYEE);
			if(temp!=null){
				Employee emp = this.employeeService.getById(appoint.getEmployeeId());
				
				WxMpTemplateMessage message = new WxMpTemplateMessage();
				message.setUrl(this.webSite+EMPLOYEE_ORDER_URL);
				message.setTouser(emp.getOperId());
				
				message.setTemplate_id(temp.getTemplateId());
				message.setTopcolor("#FF0000");
				
				/**
				 * 模板
				 * {{first.DATA}}
					客户姓名：{{keyword1.DATA}}
					客户手机：{{keyword2.DATA}}
					预约时间：{{keyword3.DATA}}
					预约内容：{{keyword4.DATA}}
					{{remark.DATA}}
				 */
				message.getData().put("first", new WxMpTemplateData("有新的会员预约，请及时确认"));
				message.getData().put("keyword1", new WxMpTemplateData(vip.getName()));
				message.getData().put("keyword2", new WxMpTemplateData(vip.getPhoneNo()));
				message.getData().put("keyword3", new WxMpTemplateData(DateUtil.date2Str(appoint.getAppointmentTime(), DateUtil.MMDDHHmm)));
				message.getData().put("keyword4", new WxMpTemplateData(appointServiceItem.getItemName()));
				message.getData().put("remark", new WxMpTemplateData("\n点击确认预约，或拒绝预约。"));
				
				employeeWxService.templateSend(message);
			}
			this.appointService.saveAppoint(appoint, appointServiceItem);
		}catch(Exception e){
			e.printStackTrace();
			log.error("预约失败：{}",e.getMessage());
			return ResultMsgFactory.fail("预约失败");
		}
		return ResultMsgFactory.success("预约成功");
	}
	
	@RequestMapping(value = "myOrder")
	public String myOrder(Model model,HttpSession session) {
		// TODO Auto-generated method stub
		return viewName("my_order");
	}
	
	@RequestMapping(value = "myOrderPage")
	@ResponseBody
	public Page<Appointment> myOrderPage(Model model,HttpSession session,Querier querier) {
		// TODO Auto-generated method stub
		Vip vip = (Vip)session.getAttribute("wxVip");
		Appointment appoint = new Appointment();
		appoint.setVipId(vip.getVipId());
		Page<Appointment> page = this.appointService.queryByPage(querier, appoint);
		return page;
	}
	
	@RequestMapping(value = "myEvaluate")
	public String myEvaluate(Model model,HttpSession session) {
		// TODO Auto-generated method stub
		return viewName("my_evaluate");
	}
	
	@RequestMapping(value = "myEvaluatePage")
	@ResponseBody
	public Page<OrderInfo> myEvaluatePage(Model model,HttpSession session,Querier querier) {
		// TODO Auto-generated method stub
		Vip vip = (Vip)session.getAttribute("wxVip");
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setVipId(vip.getVipId());
		orderInfo.setState(Constant.ORDER_STATE_OVER);
		Page<OrderInfo> page = this.orderInfoService.queryByPageFromWx(querier, orderInfo);
		return page;
	}
	
	@RequestMapping(value = "evaluate/{orderId}", method = RequestMethod.GET)
	@ResponseBody
	public List<OrderSchedule> evaluate(@PathVariable String orderId) {
		// TODO Auto-generated method stub
		OrderSchedule t = new OrderSchedule();
		t.setOrderInfoId(orderId);
		List<OrderSchedule> list = this.scheService.queryList(t);
		return list;
	}
	
	@RequestMapping(value = "evaluate", method = RequestMethod.POST)
	@ResponseBody
	public ResultMsg evaluateSave(OrderInfo orderInfo,HttpSession session) {
		// TODO Auto-generated method stub
		try{
			Vip vip = (Vip)session.getAttribute("wxVip");
			orderInfo.setCompId(vip.getCompId());
			this.orderInfoService.saveOrderEvaluate(orderInfo);
		}catch(Exception e){
			e.printStackTrace();
			log.error("评价失败：{}",e.getMessage());
			return ResultMsgFactory.fail("评价失败");
		}
		return ResultMsgFactory.success("评价成功");
	}
	
	@RequestMapping(value = "service")
	public String service(Model model,HttpSession session) {
		// TODO Auto-generated method stub
		List<Shop> shopList = this.shopService.getShopListByCompId(Constant.comp.getCompId());
		model.addAttribute("shopList", shopList);
		if(session.getAttribute("wxVip")!=null){
			Vip vip = (Vip)session.getAttribute("wxVip");
			if(vip.getShopId()!=null){
				model.addAttribute("vipShopId", vip.getShopId());
			}
		}
		
		return viewName("service");
	}
	
	@RequestMapping(value = "service/{shopId}", method = RequestMethod.GET)
	@ResponseBody
	public PageMap<ServiceItemPrice> service(Model model,HttpSession session,@PathVariable String shopId) {
		// TODO Auto-generated method stub
		Map<String, List<ServiceItemPrice>> map = new LinkedHashMap<>();
		List<ServiceItemPrice> priceList = this.itemService.getPriceListByShop(shopId);
		List<PackagePrice> packagePriceList = this.packageService.getPackagePriceByShopId(shopId);
		if(priceList!=null&& priceList.size()>0){
			for(ServiceItemPrice price:priceList){
				List<ServiceItemPrice> tmpList= map.get(price.getItemCategoryName());
    			if(tmpList==null){
    				tmpList = new ArrayList<>();
    				map.put(price.getItemCategoryName(), tmpList);
    			}
    			tmpList.add(price);
			}
		}
		
		if(packagePriceList!=null && packagePriceList.size()>0){
			String packageCate = "套餐篇";
			map.put(packageCate, new ArrayList<ServiceItemPrice>());
			for(PackagePrice price:packagePriceList){
				ServiceItemPrice item = new ServiceItemPrice();
				item.setItemCategoryName(packageCate);
				item.setServiceItemName(price.getPackageName());
				item.setNoVipPrice(price.getNoVipPrice());
				item.setVipPrice(price.getVipPrice());
				item.setServiceItemId(price.getPackageId());
    			map.get(packageCate).add(item);
			}
		}
		PageMap<ServiceItemPrice> page = new PageMap<>();
		page.setRowsMap(map);
		page.setRecords(map.size());
		return page;
	}
	
	@RequestMapping(value = "shopEmployee/{shopId}", method = RequestMethod.GET)
	@ResponseBody
	public List<Employee> shopEmployee(Model model,HttpSession session,@PathVariable String shopId) {
		// TODO Auto-generated method stub
		return this.employeeService.getEmployeeListByShopIdAndHasOperId(shopId);
	}
	
	@RequestMapping(value = "employeeWorks/{employeeId}", method = RequestMethod.GET)
	@ResponseBody
	public List<Works> employeeWorks(@PathVariable String employeeId) {
		// TODO Auto-generated method stub
		return this.worksService.getWorksListByEmployeeId(employeeId);
	}
	
	@RequestMapping(value = "orderEmpSelect", method = RequestMethod.POST)
	@ResponseBody
	public ResultMsg orderEmpSelect(String employeeId,String shopId) {
		// TODO Auto-generated method stub
		Map<String, Object> map = new LinkedHashMap<>();
		
		List<Holiday> holidayList = this.holidayService.getHolidayListByEmployeeId(employeeId);
		List<Appointment> appList = this.appointService.getSuccessByEmployee(employeeId);
		if(holidayList!=null){
			for(Holiday hol:holidayList){
				EmpAppointTime emp = new EmpAppointTime();
				emp.setHoliday(true);
				map.put(CommUtil.formatDate(hol.getRestDate()), emp);
			}
		}
		String timeFormat = "HH:mm";
		if(appList!=null){
			for(Appointment app:appList){
				String date = CommUtil.formatDate(app.getAppointmentTime());
				Object obj= map.get(date);
    			if(obj==null){
    				EmpAppointTime emp = new EmpAppointTime();
    				emp.setAppointTime(new ArrayList<String>());
    				emp.getAppointTime().add(CommUtil.formatDate(app.getAppointmentTime(),timeFormat));
    				map.put(date, emp);
    			}else{
    				EmpAppointTime emp = (EmpAppointTime)obj;
    				if(emp.getAppointTime()==null){
    					emp.setAppointTime(new ArrayList<String>());
    				}
    				emp.getAppointTime().add(CommUtil.formatDate(app.getAppointmentTime(),timeFormat));
    			}
			}
		}
		List<ServiceItem> list = this.itemService.getItemListByEmployAndShop(employeeId, shopId);
		map.put("serviceList", list);
		ResultMsg resultMsg = ResultMsgFactory.successMsg();
		resultMsg.setParams(map);
		return resultMsg;
	}
	
	/**
	 * 获取员工的不可预约时间(合并到上面接口)
	 * @param session
	 * @param employeeId
	 * @return
	 */
	@RequestMapping(value = "empAppointTime/{employeeId}", method = RequestMethod.GET)
	@ResponseBody
	public ResultMsg empAppointTime(HttpSession session,@PathVariable String employeeId) {
		// TODO Auto-generated method stub
		Map<String, Object> map = new LinkedHashMap<>();
		
		List<Holiday> holidayList = this.holidayService.getHolidayListByEmployeeId(employeeId);
		List<Appointment> appList = this.appointService.getSuccessByEmployee(employeeId);
		if(holidayList!=null){
			for(Holiday hol:holidayList){
				EmpAppointTime emp = new EmpAppointTime();
				emp.setHoliday(true);
				map.put(CommUtil.formatDate(hol.getRestDate()), emp);
			}
		}
		String timeFormat = "HH:mm";
		if(appList!=null){
			for(Appointment app:appList){
				String date = CommUtil.formatDate(app.getAppointmentTime());
				Object obj= map.get(date);
    			if(obj==null){
    				EmpAppointTime emp = new EmpAppointTime();
    				emp.setAppointTime(new ArrayList<String>());
    				emp.getAppointTime().add(CommUtil.formatDate(app.getAppointmentTime(),timeFormat));
    				map.put(date, emp);
    			}else{
    				EmpAppointTime emp = (EmpAppointTime)obj;
    				if(emp.getAppointTime()==null){
    					emp.setAppointTime(new ArrayList<String>());
    				}
    				emp.getAppointTime().add(CommUtil.formatDate(app.getAppointmentTime(),timeFormat));
    			}
			}
		}
		ResultMsg resultMsg = ResultMsgFactory.successMsg();
		resultMsg.setParams(map);
		return resultMsg;
	}
	
	/**
	 * 微信统一下单
	 * @param amount
	 */
	@RequestMapping(value = "unifiedorder", method = RequestMethod.POST)
	@ResponseBody
	public ResultMsg unifiedorder(HttpSession session,HttpServletRequest request,BigDecimal amount){
		Vip vip = (Vip)session.getAttribute("wxVip");
		String czNo = CodecUtils.getRechargeNo();
		Map<String, Object> map = new LinkedHashMap<>();
		PayFlow payFlow = null;
		try{
			payFlow = new PayFlow();
			payFlow.setPayFlowId(CodecUtils.getUUID());
			payFlow.setCompId(vip.getCompId());
			payFlow.setVipId(vip.getVipId());
			payFlow.setFlowNo(czNo);
			payFlow.setAmount(amount);
			payFlow.setPaySource(Constant.PAY_SOURCE_CZ);
			payFlow.setPayWay(Constant.PAY_WAY_ZX);
			payFlow.setTradeType(WxTradeType.JSAPI.toString());
			payFlow.setStatedate(new Date());
			
			this.payFlowService.save(payFlow);
		}catch(Exception e){
			e.printStackTrace();
			log.error("下单失败：{}",e.getMessage());
			return ResultMsgFactory.fail("充值失败，请稍后重试");
		}
		try{
			Map<String, String> payInfo=vipWxService.getJSSDKPayInfo(vip.getOperId(), czNo, amount, "会员卡余额充值", WxTradeType.JSAPI.toString(), IpUtil.getIpAddr(request), this.webSite+Constant.WX_PAY_NOTIFY_URL);
			map.put("payInfo", payInfo);
			map.put("no", czNo);
			ResultMsg resultMsg = ResultMsgFactory.successMsg();
			resultMsg.setParams(map);
			return resultMsg;
		}catch(Exception e){
			payFlow.setPayResult(PayResult.PAYERROR.toString());
			payFlow.setTradeStateDesc("微信统一下单失败"+e.getMessage());
			payFlow.setCompleteTime(new Date());
			this.payFlowService.update(payFlow);
			
			e.printStackTrace();
			log.error("微信预下单失败：{}",e.getMessage());
			return ResultMsgFactory.fail("充值失败，请稍后重试");
		}
	}
	
	/**
	 * 微信查询订单是否支付成功
	 * @param amount
	 */
	@RequestMapping(value = "payQuery", method = RequestMethod.POST)
	@ResponseBody
	public ResultMsg payQuery(HttpSession session,String no){
		Vip vip = (Vip)session.getAttribute("wxVip");
		try{
			ResultMsg resultMsg = this.payFlowService.checkCzWxPayInfo(no, null);
			if(resultMsg.isSuccess()){
				vip = this.vipService.getById(vip.getVipId());
				session.setAttribute("wxVip", vip);
				resultMsg.addParam("balance", vip.getBalance());
				resultMsg.setMsg("充值成功，您当前余额为："+vip.getBalance());
			}
			return resultMsg;
		}catch(Exception e){
			e.printStackTrace();
			log.error("充值失败：{}",e.getMessage());
			return ResultMsgFactory.fail("充值失败，请稍后重试");
		}
	}
	
	@RequestMapping(value = "coupon")
	public String coupon(Model model,HttpSession session) {
		// TODO Auto-generated method stub
		Vip vip = (Vip)session.getAttribute("wxVip");
		List<CouponReceive> list = this.couponReceiveService.getListByVipId(vip.getVipId());
		model.addAttribute("list", list);
		return viewName("coupon");
	}
	
	/**
	 * 领取卡券
	 * @return
	 */
	@RequestMapping(value = "coupon/receive/{couponId}", method = RequestMethod.GET)
	public String couponReceive(RedirectAttributes redirectAttr,HttpSession session,@PathVariable String couponId) {
		// TODO Auto-generated method stub
		Vip vip = (Vip)session.getAttribute("wxVip");
		try{
			CouponReceive cr = this.couponReceiveService.getByVipIdAndCouponId(vip.getVipId(), couponId);
			if(cr!=null){
				redirectAttr.addFlashAttribute("resultMsg",
						ResultMsgFactory.success("该卡券已领取过，不能重复领取"));
			}else{
				ResultMsg msg = this.couponReceiveService.receiveCoupon(vip, couponId);
				redirectAttr.addFlashAttribute("resultMsg",msg);
			}
		}catch(Exception e){
			e.printStackTrace();
			log.error("领取卡券失败：{}",e.getMessage());
			redirectAttr.addFlashAttribute("resultMsg",
					ResultMsgFactory.fail("领取失败"));
		}
		return redirectToUrl(viewName("coupon"));
	}
}
